import 'dart:async';
import 'dart:io';

import 'package:chewie/chewie.dart';
import 'package:eyepetizer_example/utils/toast_util.dart';
import 'package:eyepetizer_example/widget/go_navigation.dart';

// import 'package:chewie/src/material/material_progress_bar.dart';// chewie 2.12 导包
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:orientation/orientation.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/src/material/material_progress_bar.dart';

import '../utils/format_duration_util.dart';

///自定义播放器UI
class VideoControlsWidget extends StatefulWidget {
  // 初始化是是否显示 加载动画：默认为true
  final bool showLoadingOnInitialize;

  // 是否显示大播放按钮：默认为true
  final bool showBigPlayIcon;

  // 浮层 Ui
  final Widget overlayUI;

  // 底层控制栏的背景色：一般设为渐变色
  final Gradient bottomGradient;

  const VideoControlsWidget(
      {Key? key,
        this.showLoadingOnInitialize = true,
        this.showBigPlayIcon = true,
        required this.overlayUI,
        required this.bottomGradient})
      : super(key: key);


  @override
  State<VideoControlsWidget> createState() => _VideoControlsWidgetState();
}

// SingleTickerProviderStateMixin:ticker,定义 AnimationController 需要
class _VideoControlsWidgetState extends State<VideoControlsWidget> with SingleTickerProviderStateMixin{

  late AnimationController _animationController;
  late ChewieController chewieController;
  late VideoPlayerController controller;

  bool _initWidget = false;
  // 控制栏隐藏时间计时器
  Timer? _hideTimer;
  Timer? _initTimer;
  // 全屏切换 Timer
  Timer? _showAfterExpandCollapseTimer;

  @override
  void dispose() {
    _dispose();
    _initWidget = false;
    super.dispose();
  }

  void _dispose() {
    controller.removeListener(_updateState);
    _hideTimer?.cancel();
    _initTimer?.cancel();
    _showAfterExpandCollapseTimer?.cancel();
  }

  @override
  void didChangeDependencies() {
    _initPlayWidget();
    super.didChangeDependencies();
  }

  void _initPlayWidget() {
    if(!_initWidget) {
      _animationController = AnimationController(
        vsync: this,
        duration: const Duration(milliseconds: 400),
        reverseDuration: const Duration(milliseconds: 400),
      );

      chewieController = ChewieController.of(context);
      controller = chewieController.videoPlayerController;

      _initialize();
    }
    _initWidget = true;
  }

  late VideoPlayerValue _latestValue;

  /// 初始化
  Future<void> _initialize() async {
    controller.addListener(_updateState);
    // 更新状态：重新获取视频播放的状态数据
    _updateState();
    if ((controller.value.isPlaying) ||
        chewieController.autoPlay) {
      _startHideTimer();
    }

    if (chewieController.showControlsOnInitialize) {
      _initTimer = Timer(const Duration(milliseconds: 200), () {
        setState(() {
          _hideStuff = false;
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return _playVideo();
  }

  Widget _playVideo() {
    return GestureDetector(
      onTap: ()=> _cancelAndRestartTimer(),
      child: AbsorbPointer(
        // absorbing：true 不响应事件
        absorbing: _hideStuff,
        child: Stack(
          children: [
            Column(
              children: [
                //点击区域
                _buildHitArea(),
                // 底部控制栏
                _buildBottomBar(context),
              ],
            ),
            // 浮层
            _overlayUI()
          ],
        ),
      )
    );
  }

  /// 取消并重新开始计时：隐藏时间
  void _cancelAndRestartTimer() {
    _hideTimer?.cancel();
    _startHideTimer();

    setState(() {
      _hideStuff = false;
      _displayTapped = true;
    });
  }

  /// 开始隐藏时间计时
  void _startHideTimer() {
    _hideTimer = Timer(const Duration(seconds: 3), () {
      setState(() {
        _hideStuff = true;
      });
    });
  }

  bool _displayTapped = false;
  _buildHitArea() {
    return Expanded(child: GestureDetector(
      onTap: (){
        // 显示隐藏控制栏
        if (_latestValue.isPlaying) {
          if (_displayTapped) {
            setState(() {
              _hideStuff = true;
            });
          } else {
            _cancelAndRestartTimer();
          }
        } else {
          setState(() {
            _hideStuff = true;
          });
        }
      },
      child: Container(
        color: Colors.transparent,
        child: AnimatedOpacity(
          opacity: !_latestValue.isPlaying && !_dragging
              ? 1.0
              : 0.0,
          duration: const Duration(microseconds: 300),
          child: _palyPauseButton(true),
        ),
      ),
    ));
  }

  // 底部控制栏的高度
  final barHeight = 48.0;
  final marginSize = 5.0;

  Widget _buildBottomBar(BuildContext context) {
    final iconColor = Theme.of(context).textTheme.button?.color;
    return AnimatedOpacity(
      opacity:  _hideStuff ? 0.0 : 1.0,
      duration: const Duration(microseconds: 300),
      child: Container(
        height: barHeight,
        //背景色：渐变
        decoration: BoxDecoration(gradient: widget.bottomGradient),
        child: Row(
          children: [
            // 暂停和播放icon
            _buildPlayPause(),

            if(chewieController.isLive)
              const SizedBox()
            else
              _buildProgressBar(),
            if(chewieController.isLive)
              const Expanded(child: Text("LIVE"),)
            else
            //显示播放时间
            _buildPlayTime(),
            // 是否显示播放速度设置按钮
            if (chewieController.allowPlaybackSpeedChanging)
              _buildSpeedButton(controller),
            // 音量按钮
            if (chewieController.allowMuting)
              _buildMuteButton(controller),
            // 全屏按钮
            if (chewieController.allowFullScreen)
              _buildExpandButton(),
          ],
        ),
      ),
    );
  }

  _buildExpandButton()=> GestureDetector(
    onTap: (){
      _onExpandCollapse();
    },
    child: Container(
      height: barHeight,
      padding: const EdgeInsets.only(left: 8.0, right: 8.0),
      child: Icon(
        chewieController.isFullScreen ? Icons.fullscreen_exit_rounded : Icons.fullscreen,
        color: Colors.white,
      ),
    ),
  );

  //横竖屏切换
  void _onExpandCollapse() {
    setState(() {
      _hideStuff = true;
      if(Platform.isAndroid) {
        chewieController.toggleFullScreen();
      }else {
        AppToast.showTip("暂不支持IOS屏幕切换");
      }
      _showAfterExpandCollapseTimer =
          Timer(const Duration(milliseconds: 300), () {
            setState(() {
              _cancelAndRestartTimer();
            });
          });
    });
  }

  double _latestVolume = 0.5;
  _buildMuteButton(controller)=> GestureDetector (
    onTap: (){
      _cancelAndRestartTimer();
      if(_latestValue.volume == 0) {
        controller.setVolume(_latestVolume);
      }else {
        _latestVolume = _latestValue.volume;
        controller.setVolume(0.0);
      }
    },

    child: Container(
      height: barHeight,
      padding: const EdgeInsets.only(left: 8.0, right: 8.0),
      child: Icon(
        _latestValue.volume > 0 ? Icons.volume_up : Icons.volume_off,
        color: Colors.white,
      ),
    ),
  );

  _buildSpeedButton(controller)=> GestureDetector(
    onTap: ()async {
      _hideTimer?.cancel();
      if (_latestValue.isPlaying) {
        _startHideTimer();
      }
    },
    child: Container(
      height: barHeight,
      padding: const EdgeInsets.only(left: 8.0, right: 8.0),
      child: const Icon(Icons.speed, color: Colors.white,),
    ),
  );

  Widget _buildPlayTime() {
    Duration position = _latestValue.position;
    Duration duration = _latestValue.duration;
    return Padding(padding: const EdgeInsets.only(right: 5.0),
    child: Text(
      "${formatDuration(position)}/${formatDuration(duration)}",
      style: const TextStyle(fontSize: 10, color: Colors.white),
    ),
    );
  }

  GestureDetector _buildPlayPause() {
    return GestureDetector(
      onTap: (){
        _playPause();
      },
      child: Container(
        height: barHeight,
        color: Colors.transparent,
        padding: const EdgeInsets.only(left: 10.0, right: 10.0),
        child:  Icon(
           controller.value.isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded,
          color: Colors.white
        ),
      ),
    );
  }


  /// 更新状态：重新获取视频播放的状态数据
  void _updateState() {
    setState(() {
      _latestValue = controller.value;
    });
  }

  bool _hideStuff = true;
  void _playPause() {
    var isFinished = _latestValue.position >= _latestValue.duration;
    setState(() {
      //如果正在播放
      if (controller.value.isPlaying) {
        // 方向执行动画：从播放到暂停
        _animationController.reverse();
        _hideStuff = false;
        controller.pause();
      } else {
        _cancelAndRestartTimer();

        if (!controller.value.isInitialized) {
          controller.initialize().then((_) {
            controller.play();
            // 正向执行动画：从暂停到播放
            _animationController.forward();
          });
        } else {
          // 如果播放完，跳转到开始
          if (isFinished) {
            controller.seekTo(const Duration());
          }
          // 正向执行动画：从暂停到播放
          _animationController.forward();
          controller.play();
        }
      }
    });
  }

  bool isPlaying() => controller.value.isPlaying;

  _overlayUI() => AnimatedOpacity(
    opacity: _hideStuff ? 0.0 : 1.0,
    duration: const Duration(
        microseconds: 300
    ),
    child: widget.overlayUI,
  );

  Widget _palyPauseButton(isFinished) {
    return GestureDetector(
        child: Padding(
          padding: EdgeInsets.only(top: 20),
          child: Center(
            child: ClipOval(
              child: Material(
                child: IconButton(
                  icon: isFinished ? const Icon(Icons.replay, size: 32.0) :
                      AnimatedIcon(icon: AnimatedIcons.play_pause, progress:_animationController,
                      size: 32, ),
                  onPressed: (){
                    // 开始播放或暂停
                    _playPause();
                  },
                ),
              ),
            ),
          ),
        ),
    );

  }

  bool _dragging = false;
  _buildProgressBar() => Expanded(child: Padding(
    padding: const EdgeInsets.only(right: 15, left: 15),
    child: MaterialVideoProgressBar(
      controller,
      // 开始拖拽
      onDragStart:(){
        setState(() {
          // 不让底部控制栏隐藏
          _dragging = true;
        });
        _hideTimer?.cancel();
      },
      onDragEnd: (){
        setState(() {
          _dragging = false;
        });
        _startHideTimer();
      },
      colors:  ChewieProgressColors(
          playedColor: Theme.of(context).accentColor,
          handleColor: Theme.of(context).accentColor,
          bufferedColor: Theme.of(context).backgroundColor,
          backgroundColor: Theme.of(context).disabledColor),
    ),
  ));

}

